package deviceinfo.wsm.com.deviceinfo.upload;

import android.util.Log;


import java.io.IOException;
import java.util.TreeMap;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ${chengmouyong} on 2018/4/12 09:29
 * Explain：
 */

public class HttpClient {

    private static Retrofit retrofit;

    private HttpClient() {
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                // Customize the request header
                Request request = original.newBuilder()
                        .header("Accept", "application/json")
                        .header("Cookie", "Set-Cookie")
                        .method(original.method(), original.body())
                        .build();
                Response response = chain.proceed(request);
                // Customize or return the response
                return response;
            }
        })

//                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
//                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();


        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BaseParams.URI)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

//            service = retrofit.create(NetWorkInterfaces.class);
        }
    }


    /**
     * 调用单例对象
     */
    private static HttpClient getInstance() {
        return HttpClientInstance.instance;
    }

    private static HttpClient getInstance(String lgtoken) {
        return HttpClientInstance.instance;
    }

    /**
     * 创建单例对象
     */
    private static class HttpClientInstance {
        static HttpClient instance = new HttpClient();
    }

    private static TreeMap<String, Object> serviceMap;

    private static TreeMap<String, Object> getServiceMap() {
        if (serviceMap == null)
            serviceMap = new TreeMap<>();
        return serviceMap;
    }

    /**
     * @return 指定service实例
     */
    public static <T> T getService(Class<T> clazz) {
        if (getServiceMap().containsKey(clazz.getSimpleName())) {
            return (T) getServiceMap().get(clazz.getSimpleName());
        }

        Log.w("RDClient", "need to create a new " + clazz.getSimpleName());
        T service = HttpClient.getInstance().retrofit.create(clazz);
        getServiceMap().put(clazz.getSimpleName(), service);
        return service;
    }
}
